﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using Utility;
using Model.Modules;
using System.Data.Entity;
using System.Windows;
using System.Windows.Threading;

using System.Timers;
using Model;
using Newtonsoft.Json;
using System.IO;
using System.Collections.ObjectModel;
using System.Data.Entity.Migrations;
using MySql.Data.MySqlClient;
using ViewModel.VM.Control;
using System.Diagnostics;
using Proxy;

namespace ViewModel
{
    public class VM_WindowGradeConfig : BaseViewModel
    {
        surfacedetectEntities surfaceEntities = new surfacedetectEntities();
        public string GradeDescription { get; set; }
        public ObservableCollection<gradeconfig> GradeConfigList { get; set; }
        public gradeconfig CurrentGradeConfig
        {
            get { return _currentGradeConfig; }
            set
            {
                _currentGradeConfig = value;
                OnPropertyChanged();
                updateConfig();

            }
        }
        gradeconfig _currentGradeConfig;

        public gradeconfig UsedGradeConfig { get; set; }

        public GradeConfig ScoreConfig { get { return scoreConfig; } set { scoreConfig = value; OnPropertyChanged(); } }
        private GradeConfig scoreConfig;

        public ObservableCollection<Unit> UnitList { get { return unitList; } set { unitList = value; OnPropertyChanged(); } }
        private ObservableCollection<Unit> unitList;

        public ObservableCollection<DefectType> DefectTypeList { get { return defectTypeList; } set { defectTypeList = value; OnPropertyChanged(); } }
        private ObservableCollection<DefectType> defectTypeList;
        public sysconfig sysconfig { get; set; }

        public VM_WindowGradeConfig()
        {
            initData();
            try
            {
                var surfaceEntities = new surfacedetectEntities();
                GradeConfigList =new ObservableCollection<gradeconfig>(surfaceEntities.gradeconfig.ToList());
                try
                {
                    int gradeconfigid = int.Parse(surfaceEntities.sysconfig.Where(t => t.key == "gradeconfigid").FirstOrDefault().value);
                    if (GradeConfigList.Where(t => t.id == gradeconfigid).Any())
                    {
                        UsedGradeConfig = GradeConfigList.Where(t => t.id == gradeconfigid).First();
                        CurrentGradeConfig = UsedGradeConfig;
                        ScoreConfig= JsonConvert.DeserializeObject<GradeConfig>(CurrentGradeConfig.config);
                    }

                    else
                        CurrentGradeConfig = new gradeconfig() { id = -1, name = "未设置" };
                }
                catch (Exception)
                {
                    CurrentGradeConfig=new gradeconfig() { id=-1,name="未设置"};
                }

                //surfaceEntities.sysconfig.ToList().ForEach(entity => { 
                //    if (entity.key== "gradeconfig")
                //    {
                //        sysconfig=entity;
                //        if (!string.IsNullOrEmpty(sysconfig.value))
                //        {
                //            ScoreConfig = JsonConvert.DeserializeObject<GradeConfig>(entity.value);
                //        }
                //    }
                //});
                //if (ScoreConfig == null)
                //    ScoreConfig = JsonConvert.DeserializeObject<GradeConfig>(File.ReadAllText(Path.Combine(System.Environment.CurrentDirectory, "steel_det_cfg.json")));
                
            }
            catch (Exception e)
            {

            }


        }


        private void initData() {
            sysconfig=new sysconfig() { key="gradeconfig"};
            GradeDescription=SysConfig.GetInstance().GetAttributeValue("/sysconfig/view/PageMonitor/GradeDescription", "text");

        }

        

        //public BaseCommand SaveCommand { get => new BaseCommand(SaveCommand_Executed); }
        //public void SaveCommand_Executed(object obj)
        //{

        //    var contents=JsonConvert.SerializeObject(ScoreConfig,Formatting.Indented,new JsonSerializerSettings() {  NullValueHandling= NullValueHandling.Ignore});
        //    sysconfig.value = contents;
        //    var surfaceEntities = new surfacedetectEntities();
        //    try
        //    {
        //        surfaceEntities.sysconfig.AddOrUpdate(sysconfig);
        //        surfaceEntities.SaveChanges();
        //    }
        //    catch (Exception e)
        //    {
        //        MessageBox("未能保存成功到数据库，保存为本地配置");
        //    }

            
        //    File.WriteAllText(Path.Combine(System.Environment.CurrentDirectory, "steel_det_cfg.json"), contents);
        //    this.Close();
        //}


        public BaseCommand CancelCommand { get => new BaseCommand(CancelCommand_Executed); }

        private void CancelCommand_Executed(object obj)
        {
            VM_WindowMain.GetInstance().UpdateGradeCofig();
            this.Close();
        }

        #region 增删改套餐
        /// <summary>
        /// 添加过滤器
        /// </summary>
        public BaseCommand AddGradeConfigCMD
        {
            get => new BaseCommand((obj) =>
            {

                var dlg = new VM_WindowTextBoxDlg("请输入新套餐名称");
                dlg.ShowDialog();
                if ((dlg.UIElement as Window).DialogResult != true)
                    return;
                if (GradeConfigList.Select(s => s.name).Contains(dlg.Text))
                {
                    MessageBox(this.UIElement as Window, "套餐列表中已经存在该名称，添加失败");
                    return;
                }
                var config = new surfacedetectEntities().sysconfig.Where(t=>t.key=="gradeconfig").FirstOrDefault().value;
                surfaceEntities.gradeconfig.Add(new gradeconfig() { name=dlg.Text,config=config });
                if (surfaceEntities.SaveChanges() != 1)
                {
                    MessageBox(this.UIElement as Window, "保存失败");
                    Logger.Info($"添加自定义评级套餐：{dlg.Text}失败");
                }
                GradeConfigList = new ObservableCollection<gradeconfig>(surfaceEntities.gradeconfig.AsNoTracking().ToList());
                CurrentGradeConfig = GradeConfigList.Where(t => t.name == dlg.Text).First();
            });
        }

        public BaseCommand RemoveGradeConfigCMD
        {
            get => new BaseCommand((obj) =>
            {
                var index = GradeConfigList.IndexOf(CurrentGradeConfig);
                if (index <= 0)
                {
                    MessageBox(this.UIElement as Window, "默认套餐无法删除,请选择其他自定义套餐");
                    return;
                }
                if (CurrentGradeConfig.id== UsedGradeConfig.id)
                {
                    MessageBox(this.UIElement as Window, "当前套餐正在用于评级，请将系统使用套餐更改为其他套餐后，再删除此套餐");
                    return;
                }

                MessageBox(this.UIElement as Window, $"请确认是否删除名称为{CurrentGradeConfig.name}的评级套餐？", new Action<bool>((confirm) =>
                {
                    if (confirm)
                    {
                        var deletedgradeconfig = surfaceEntities.gradeconfig.Where(t => t.id == CurrentGradeConfig.id).First();
                        surfaceEntities.gradeconfig.Remove(deletedgradeconfig);
                        if (surfaceEntities.SaveChanges() < 1)
                        {
                            MessageBox("删除失败");
                            Logger.Info($"删除自定义评级套餐：{CurrentGradeConfig.name}失败");
                        }
                        GradeConfigList = new ObservableCollection<gradeconfig>(surfaceEntities.gradeconfig.AsNoTracking().ToList());
                        CurrentGradeConfig = GradeConfigList[index - 1];
                    }
                }));
            });
        }

        /// <summary>
        /// 修改过滤器名称
        /// </summary>
        public BaseCommand ModifyGradeConfigNameCMD
        {
            get => new BaseCommand((obj) =>
            {

                var dlg = new VM_WindowTextBoxDlg("请修改名称", CurrentGradeConfig.name);
                dlg.ShowDialog();
                if ((dlg.UIElement as Window).DialogResult != true)
                    return;
                if (GradeConfigList.Select(s => s.name).Contains(dlg.Text))
                {
                    MessageBox(this.UIElement as Window, "套餐列表中已经存在该名称或未修改缺陷名称，修改失败");
                    return;
                }
                CurrentGradeConfig.name=dlg.Text;
                surfaceEntities.gradeconfig.AddOrUpdate(CurrentGradeConfig);
                if (surfaceEntities.SaveChanges() != 1)
                {
                    MessageBox(this.UIElement as Window, "保存失败");
                    Logger.Info($"修改自定义套餐：{CurrentGradeConfig.name}失败");
                }
            });
        }



        /// <summary>
        /// 保存过滤器内容修改
        /// </summary>
        public BaseCommand SaveCommand
        {
            get => new BaseCommand((obj) =>
            {
                CurrentGradeConfig.config= JsonConvert.SerializeObject(ScoreConfig, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
                surfaceEntities.gradeconfig.AddOrUpdate(CurrentGradeConfig);
                surfaceEntities.SaveChanges();
                MessageBox(this.UIElement as Window, "保存成功");
            });
        }


        /// <summary>
        /// 还原过滤器修改
        /// </summary>
        public BaseCommand ResetGradeConfigCMD
        {
            get => new BaseCommand((obj) =>
            {
                //string fitlername = CurrentGradeConfig.name;
                //GradeConfigList = SteelDefectFilterHelper.ConvertFilterRecordsToModels(surfaceEntities.defect_filter.ToList());
                //CurrentGradeConfig = GradeConfigList.Where(t => t.name == fitlername).First();
            });
        }

        private void updateConfig()
        {
            if (CurrentGradeConfig == null|| string.IsNullOrEmpty(CurrentGradeConfig.config))
                return;
            ScoreConfig = JsonConvert.DeserializeObject<GradeConfig>(CurrentGradeConfig.config);
        }
        /// <summary>
        /// 应用当前套餐
        /// </summary>
        public BaseCommand ApplyCommand
        {
            get => new BaseCommand((obj) =>
            {
                if (CurrentGradeConfig != null)
                {
                    UsedGradeConfig = CurrentGradeConfig;
                    surfaceEntities.sysconfig.Where(t => t.key == "gradeconfigid").FirstOrDefault().value = CurrentGradeConfig.id.ToString();
                    surfaceEntities.SaveChanges();
                }


            });
        }
        
        #endregion
    }

}
